import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../axios/index'


Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    sidebar: true,
    mask: false,
    token: '' || sessionStorage.getItem('token'),
    userId: '' || sessionStorage.getItem('userId'),
    nickname: '' || sessionStorage.getItem('nickname'),
    admin: '' || sessionStorage.getItem('admin'),
    userMess: {
      org_id: '',
      orgname: '',
      username: '',
      nickname: '',
      telphone: '',
      email: '',
    }
  },
  mutations: {
    sidebarStatus_change(state, data) {
      state.sidebar = data;
    },
    maskStatus_change(state, data) {
      state.mask = data;
    },
    auth_success(state, data) {
      state.token = data.token;
      state.userId = data.userId;
      state.nickname = data.nickname;
      state.admin = data.admin;
    },
    logout(state) {
      state.token = '';
      state.userId = '';
      state.nickname = '';
      state.admin = '';
    },
    user_mess(state, data) {
      state.userMess.org_id = data.org_id;
      state.userMess.orgname = data.orgname;
      state.userMess.username = data.username;
      state.userMess.nickname = data.nickname;
      state.userMess.telphone = data.telphone;
      state.userMess.email = data.email;
    }
  },
  actions: {
    Login({
      commit
    }, user) {
      // 向后端发送请求，验证用户名密码是否正确，请求成功接收后端返回的token值，利用commit修改store的state属性，并将token存放在sessionStorage中
      return new Promise((resolve, reject) => {
        axios.post("/user/login", user)
          .then(res => {
            if (res.data.code === '200') {
              const token = res.data.data.token;
              const userId = res.data.data.userId;
              const nickname = res.data.data.nickname;
              // const admin = res.data.data.admin;
              const iadmin = res.data.data.admin;
              let admin;
              iadmin === "true" ? admin = true : admin = false;
              sessionStorage.setItem('token', token);
              sessionStorage.setItem('userId', userId);
              sessionStorage.setItem('nickname', nickname);
              sessionStorage.setItem('admin', iadmin);
              commit('auth_success', {
                token,
                userId,
                nickname,
                admin
              })
              resolve(res);
            } else {
              resolve(res);
            }
          })
          .catch(err => {
            reject(err);
          })
      })
    },
    Logout({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        try {
          window.sessionStorage.clear();
          commit('logout')
          resolve('退出成功');
        } catch (err) {
          reject('退出失败');
        }
      })

    },

  },
  modules: {},
  getters: {
    isLoggedIn: state => !!state.token,
    isAdmin: state => state.admin === "true",
  }
})